package com.example.transaction.state;

import com.example.transaction.common.enums.StepStateEnum;
import com.example.transaction.entity.Step;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Scope("request")
@Component
public class StepStateMachine {


    @Autowired
    private List<IStepState> stepStateList;

    private IStepState getState(Step step) {
        Map<StepStateEnum, IStepState> stepStateMap = stepStateList.stream()
                .collect(Collectors.toMap(IStepState::getState, v -> v, (v1, v2) -> v1));
        StepStateEnum state = StepStateEnum.ofCode(step.getState());
        log.info("当前状态:{}", state.getName());
        IStepState stepStateService = stepStateMap.get(state);
        if (Objects.isNull(stepStateService)) {
            throw new RuntimeException("未找到相关状态类");
        }
        return stepStateService;
    }

    @Transactional
    public void start(Step step) {
        getState(step).start(step);
    }

    @Transactional
    public void finish(Step step) {
        getState(step).finish(step);
    }

    @Transactional
    public void skip(Step step) {
        getState(step).skip(step);
    }

    @Transactional
    public void fail(Step step) {
        getState(step).fail(step);
    }

    @Transactional
    public void approve(Step step) {
        getState(step).approve(step);
    }

    @Transactional
    public void rollback(Step step) {
        getState(step).rollback(step);
    }
}
